/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.apestar.modules.sys.service;

import cn.apestar.common.chat.ChatInstance;
import cn.apestar.common.persistence.Page;
import cn.apestar.common.service.CrudService;
import cn.apestar.common.utils.EncryptUtils;
import cn.apestar.common.utils.StringUtils;
import cn.apestar.modules.cache.RemoveCacheUtil;
import cn.apestar.modules.sys.dao.WtUserDao;
import cn.apestar.modules.sys.entity.ApestarUser;
import cn.apestar.modules.sys.entity.UserAndInstituion;
import cn.apestar.modules.sys.entity.UserFilter;
import cn.apestar.modules.sys.entity.WtUser;
import cn.apestar.modules.sys.utils.UserUtils;
import cn.apestar.user.api.enums.UserType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 用户表Service
 *
 * @author LVH
 * @version 2016-02-21
 */
@Service @Transactional(readOnly = true) public class UserService
    extends CrudService<WtUserDao, WtUser> {

    @Autowired private UserAndInstituionService userAndInstituionService;

    private static String encryptPassword(String inputPassword) {

        try {
            inputPassword = EncryptUtils.getMD5(EncryptUtils.getMD5(inputPassword));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputPassword;
    }

    @Override public WtUser get(String id) {

        return super.get(id);
    }

    @Override public List<WtUser> findList(WtUser user) {

        return super.findList(user);
    }

    @Override public Page<WtUser> findPage(Page<WtUser> page, WtUser user) {

        return super.findPage(page, user);
    }

    public Page<WtUser> findUserList(Page<WtUser> page, UserFilter user) {

        // TODO Auto-generated method stub
        page.setList(dao.findUserList(user, page));
        return page;
    }

    @Override @Transactional(readOnly = false) public void save(WtUser user) {

        super.save(user);
    }

    @Override @Transactional(readOnly = false) public void delete(WtUser user) {
        user.setUpdateBy(UserUtils.getUser());
        user.setUpdateDate(new Date());
        super.delete(user);
    }

    @Transactional(readOnly = false) public void updateIdentity(WtUser user) {
        dao.updateIdentity(user);
    }

    @Transactional(readOnly = false) public void saveUser(WtUser user) {

        // 如果是机构增加机构信息
        if (user.getUserAndInstituionList() != null && user.getUserAndInstituionList().size() > 0) {
            user.setInstitutionId(user.getUserAndInstituionList().get(0).getCmInstitutionId());
            user.setUserType(UserType.HR.getValue());
        } else
            user.setInstitutionId(0l);
        // TODO Auto-generated method stub
        if (user.getInstitutionId() == null)
            user.setInstitutionId(Long.decode("0"));
        if (StringUtils.isBlank(user.getId())) {
            user.preInsertInteger();
            user.setRingId(user.getPhone() + user.getApp());
            if (!StringUtils.isEmpty(user.getPassword())) {
                user.setPassword(encryptPassword(user.getPassword()));
            }
            dao.insert(user);
            initChat(user);
        } else {
            // 清除原用户机构用户缓存
            WtUser oldUser = dao.get(user.getId());
            // 更新用户数据
            user.preUpdate();
            if (!StringUtils.isEmpty(user.getPassword())) {
                user.setPassword(encryptPassword(user.getPassword()));
                // 更新环信密码
                ChatInstance.getChat(user.getApp())
                    .resetUserPassword(oldUser.getRingId(), user.getPassword());
            }
            user.setUpdateBy(UserUtils.getUser());
            dao.updateUhUser(user);
        }

        RemoveCacheUtil.removeUserCache(user.getId());

        UserAndInstituion delUserInstituion = new UserAndInstituion();
        delUserInstituion.setUserId(user.getId());
        userAndInstituionService.delete(delUserInstituion);

        if (user.getUserAndInstituionList() == null
            || user.getUserAndInstituionList().size() == 0) {
            return;
        }
        for (int i = 0; i < user.getUserAndInstituionList().size(); i++) {
            UserAndInstituion userAndInstiturion = user.getUserAndInstituionList().get(i);
            userAndInstiturion.setUserId(user.getId());
            userAndInstiturion.setDelFlagb(true);
            userAndInstiturion.setUserType(UserType.HR.getValue());
            userAndInstituionService.save(userAndInstiturion);
        }
    }

    @Transactional(readOnly = false) public void saveUserByType(WtUser user, String userType) {

        // 如果是机构增加机构信息
        if (user.getUserAndInstituionList() != null && user.getUserAndInstituionList().size() > 0) {
            user.setInstitutionId(user.getUserAndInstituionList().get(0).getCmInstitutionId());
        } else
            user.setInstitutionId(0l);
        // TODO Auto-generated method stub
        if (user.getInstitutionId() == null)
            user.setInstitutionId(Long.decode("0"));
        if (StringUtils.isBlank(user.getId())) {
            user.preInsertInteger();
            user.setRingId(user.getPhone() + user.getApp());
            if (!StringUtils.isEmpty(user.getPassword())) {
                user.setPassword(encryptPassword(user.getPassword()));
            }
            dao.insert(user);
            initChat(user);
        } else {
            // 清除原用户机构用户缓存
            WtUser oldUser = dao.get(user.getId());
            // 更新用户数据
            user.preUpdate();
            if (!StringUtils.isEmpty(user.getPassword())) {
                user.setPassword(encryptPassword(user.getPassword()));
                // 更新环信密码
                ChatInstance.getChat(user.getApp())
                    .resetUserPassword(oldUser.getRingId(), user.getPassword());
            }
            dao.update(user);
        }

        RemoveCacheUtil.removeUserCache(user.getId());
        if (user.getUserAndInstituionList() == null
            || user.getUserAndInstituionList().size() == 0) {
            return;
        }
        UserAndInstituion delUserInstituion = new UserAndInstituion();
        delUserInstituion.setUserId(user.getId());
        userAndInstituionService.delete(delUserInstituion);
        for (int i = 0; i < user.getUserAndInstituionList().size(); i++) {
            UserAndInstituion userAndInstiturion = user.getUserAndInstituionList().get(i);
            userAndInstiturion.setUserId(user.getId());
            userAndInstiturion.setDelFlagb(true);
            userAndInstiturion.setUserType(userType);
            userAndInstituionService.save(userAndInstiturion);
        }
    }

    @Transactional(readOnly = false) public void saveUserByType(WtUser user) {

        // 如果是机构增加机构信息
        if (user.getUserAndInstituionList() != null && user.getUserAndInstituionList().size() > 0) {
            user.setInstitutionId(user.getUserAndInstituionList().get(0).getCmInstitutionId());
        } else
            user.setInstitutionId(0l);
        // TODO Auto-generated method stub
        if (user.getInstitutionId() == null)
            user.setInstitutionId(Long.decode("0"));
        if (StringUtils.isBlank(user.getId())) {
            user.preInsertInteger();
            user.setRingId(user.getPhone() + user.getApp());
            if (!StringUtils.isEmpty(user.getPassword())) {
                user.setPassword(encryptPassword(user.getPassword()));
            }
            dao.insert(user);
            initChat(user);
        } else {
            // 清除原用户机构用户缓存
            WtUser oldUser = dao.get(user.getId());
            // 更新用户数据
            user.preUpdate();
            if (!StringUtils.isEmpty(user.getPassword())) {
                user.setPassword(encryptPassword(user.getPassword()));
                // 更新环信密码
                ChatInstance.getChat(user.getApp())
                    .resetUserPassword(oldUser.getRingId(), user.getPassword());
            }
            dao.update(user);
        }

        RemoveCacheUtil.removeUserCache(user.getId());
        if (user.getUserAndInstituionList() == null
            || user.getUserAndInstituionList().size() == 0) {
            return;
        }
        UserAndInstituion delUserInstituion = new UserAndInstituion();
        delUserInstituion.setUserId(user.getId());
        userAndInstituionService.delete(delUserInstituion);
        for (int i = 0; i < user.getUserAndInstituionList().size(); i++) {
            UserAndInstituion userAndInstiturion = user.getUserAndInstituionList().get(i);
            userAndInstiturion.setUserId(user.getId());
            userAndInstiturion.setDelFlagb(true);
            // userAndInstiturion.setUserType(userType);
            userAndInstituionService.save(userAndInstiturion);
        }
    }

    public void initChat(WtUser user) {

        // String key = user.getPhone() + user.getApp();
        // ChatInstance.getChat(user.getApp()).regUser(key, user.getPassword(), user.getNickName());
        // ChatInstance.getChat(user.getApp()).transmissionMessageByone(key, "欢迎来到" + AppType.text(user.getApp()), MessageType.TXT.getValue(), null);
    }

    /**
     * 根据登录名获取用户
     *
     * @param loginName
     * @return
     */
    public WtUser getUserByLoginName(String loginName, String userType, String id) {

        WtUser wtUser = new WtUser();
        wtUser.setAccount(loginName);
        wtUser.setUserType(userType);
        wtUser.setId(id);
        return dao.getByLoginName(wtUser);
    }

    @Transactional(readOnly = false) public void updateUser(WtUser user) {

        // TODO Auto-generated method stub
        dao.updateUser(user);
    }

    @Transactional(readOnly = false) public void updateType(WtUser user) {

        // TODO Auto-generated method stub
        dao.updateType(user);
    }

    public List<WtUser> getByIds(ApestarUser user) {
        return dao.getByIds(user);
    }
}